package me.wangcai.onlinechat.controller;

import com.google.gson.Gson;
import lombok.SneakyThrows;
import me.wangcai.onlinechat.model.Response;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
public class UploadImage {

    private static final Gson gson = new Gson();

    public static final String PATH = System.getProperty("user.dir") + "/uploadimages/" ;

    @SneakyThrows
    @CrossOrigin
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest request){

        if(request.getSession().getAttribute("user") == null){
            return gson.toJson(new Response("未登录",false));
        }
        if(uploadFile == null || uploadFile.isEmpty() || uploadFile.getSize() <= 0){
            return gson.toJson(new Response("文件错误",false));
        }

        String name = String.valueOf(System.currentTimeMillis());
        File file = new File(PATH + name);
        file.createNewFile();
        InputStream is = uploadFile.getInputStream();
        inputStreamToFile(is,file);
        return gson.toJson(new Response(name,true));
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createFolder(){
        new File(PATH).mkdir();
    }
}

